
#include "fs.rpc.h"
#include "fs.file.h"
#include "fs.server.h"
#include <string>
#include <sstream>

#define	package_fs_SIZE 255			/*  */
using namespace TOB;
FS_Server svr;


request * upload_request_1_svc(auth * p, struct svc_req * srq) {
	static request r;
	Log::event("Upload request...");
	bool res;
	uint32 error = svr.auth(p->nsip, std::string(p->username), std::string(p->password), &res);
	if ( !res || error != Code::Okay) { 
		Log::error("Auth error " + svr.toString(error)); 
		r.fileId = error; r.count = 0; return &r; 
	}
	r.fileId = svr.push(std::string(p->data));
	r.count  = !(p->count % package_fs_SIZE) ? p->count / package_fs_SIZE : p->count / package_fs_SIZE + 1;
	Log::event("Upload request...ok");
  return &r;
}

u_int * upload_file_1_svc(package_fs * p, struct svc_req * srq) {
	std::string fileName = svr.toString(p->fileId);
	std::string source(p->data);
	svr.f.write(svr.path + fileName, p->data, p->count);
	return &(p->fileId);
}

package_fs * download_request_1_svc(auth * p, struct svc_req * srq) {
  static package_fs pc;
	bool res = false;	
	uint32 error = svr.auth(p->nsip, std::string(p->username), std::string(p->password), &res);
	if (!res || error != Code::Okay) { pc.count = 0; return &pc; }
	if (svr.f.exists(svr.path + svr.toString(static_cast<int>(p->fileId))) != Code::Okay) { pc.count = 0; return &pc; }
	u_int size = svr.f.get_file_size(svr.path + svr.toString(static_cast<int>(p->fileId)));
	std::string fileName = svr.pop(p->fileId);	
	memcpy(pc.data, fileName.c_str(), fileName.length());
	pc.count = !(size % package_fs_SIZE) ? size / package_fs_SIZE : size / package_fs_SIZE + 1; 
	return &pc;
}

package_fs * download_1_svc(request * r, struct svc_req * srq) {
	static package_fs p;
	std::string fileName = svr.toString(r->fileId);
	char source[package_fs_SIZE];
	uint16 rbytes;	
	svr.f.read(svr.path + fileName, source, package_fs_SIZE, r->count, &rbytes);
	p.count = rbytes;
	memcpy(p.data, source, rbytes);
	return &p;
}
